package com.yh.doing.interpret_pattern;

import java.util.Stack;

/**
 * @program: design-patterns
 * @description: ${description}
 * @author: yangh0597@163.com
 * @date: 2021-03-09 17:41
 * @problem:
 **/
public class CalCulator {

    private Expression expression;


    public CalCulator(String expStr) {

        Stack<Expression> expressions = new Stack<>();

        char[] chars = expStr.toCharArray();

        Expression left = null;
        Expression right = null;


        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            switch (aChar) {
                case '+':
                    left = expressions.pop();
                    right = new VarExpression(String.valueOf(chars[++i]));
                    expressions.push(new AddExpression(left, right));
                    break;
                case '-':
                    left = expressions.pop();
                    right = new VarExpression(String.valueOf(chars[++i]));
                    expressions.push(new SubExpression(left, right));
                    break;
                default:
                    expressions.push(new VarExpression(String.valueOf(aChar)));
                    break;
            }
        }


        this.expression=expressions.pop();

    }





    public int run(Context context){
        return this.expression.interprete(context);
    }
}
